<?php

namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
use Qcloud\Cos\Client;
require_once "../extend/tencent/vendor/autoload.php";

class Register extends Controller
{
    //---------------------------------------------------------------------------------------------------------------------
    //------------------------------------ 注册 start -----------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------------------------------
    //注册页面
    public function register()
    {
        if(Request::instance()->isPost()){
            extract(input());
            $have = Db::table('up_company')
                ->where('c_username', $c_username)
                ->field('c_username')
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '已有此账号！']);
            }
            //--------------------------------------------
            $have = Db::table('up_admin')
                ->where('username', $c_username)
                ->field('username')
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '已有此账号！']);
            }
            //-----------------------------------------------------
            $today = date('Y-m-d H:i:s');
            $ss = Db::table('up_area')
                ->where('district_id','in',"$c_sheng,$c_shi,$c_qu")
                ->column('district');
            $regex = '/^[\x{4e00}-\x{9fa5}A-Za-z0-9]{1,100}$/u';
            $regex2 = "/^[a-zA-Z0-9]+$/";
            if (!preg_match($regex,$c_name)) {
                return json(['code' => 100, 'msg' => '名字只能输入汉字、字母、数字']);
            }
            if (!preg_match($regex2,$c_code)) {
                return json(['code' => 100, 'msg' => '信用代码只能输入字母、数字']);
            }
            $insert = [
                'c_name' => $c_name,
                'c_name2' => $c_name,
                'c_logo' => $c_logo,
                'c_charge_name' => $c_charge_name,
                'c_charge_phone' => $c_charge_phone,
                'c_sheng' => $c_sheng,
                'c_shi' => $c_shi,
                'c_qu' => $c_qu,
                'c_area_str' => implode($ss,','),
                'c_address' => $c_address,
                'c_faren' => $c_faren,
                'c_code' => $c_code,
                'c_code2' => $c_code,
                'c_zhizhao' => $c_zhizhao,
                'c_zhizhao2' => $c_zhizhao,
                'c_username' => $c_username,
                'c_password' => md5(md5($c_password) . config('auth_key')),
                'c_content' => $c_content,
                'c_verify' => 1,
                'c_time' => $today,
                'c_updatetime' => $today,
            ];
            Db::startTrans();// 启动事务
            try{
                $cid = Db::table('up_company')->insertGetId($insert);
                $adminid = Db::table('up_admin')->insertGetId([
                    'username' => $insert['c_username'],
                    'password' => $insert['c_password'],
                    'status' => 1,
                    'groupid' => 5,
                    'create_time' => time(),
                    'company_id' => $cid,
                ]);
                Db::name('auth_group_access')->insert(['uid'=> $adminid,'group_id'=>5]);
                Db::commit();// 提交事务
                return json(['code' => 200, 'msg' => '申请成功，请耐心等待审核']);
            }catch( \Exception $e){
                Db::rollback ();//回滚事务
                return json(['code' => 100, 'msg' => '申请失败，请刷新重试']);
            }
        }
        // 省
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $this->assign([
            'province' => $province,
        ]);
        return $this->fetch('/register');
    }
    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function editCom(){
        if(Request::instance()->isPost()){
            extract(input());
            $ss = Db::table('up_area')
                ->where('district_id','in',"$c_sheng,$c_shi,$c_qu")
                ->column('district');
            $regex = '/^[\x{4e00}-\x{9fa5}A-Za-z0-9]{1,100}$/u';
            $regex2 = "/^[a-zA-Z0-9]+$/";
            if (!preg_match($regex,$c_name)) {
                return json(['code' => 100, 'msg' => '名字只能输入汉字、字母、数字']);
            }
            if (!preg_match($regex2,$c_code)) {
                return json(['code' => 100, 'msg' => '信用代码只能输入字母、数字']);
            }
            $update = [
                'c_name' => $c_name,
                'c_name2' => $c_name,
                'c_logo' => $c_logo,
                'c_charge_name' => $c_charge_name,
                'c_charge_phone' => $c_charge_phone,
                'c_sheng' => $c_sheng,
                'c_shi' => $c_shi,
                'c_qu' => $c_qu,
                'c_area_str' => implode($ss,','),
                'c_address' => $c_address,
                'c_faren' => $c_faren,
                'c_code' => $c_code,
                'c_code2' => $c_code,
                'c_zhizhao' => $c_zhizhao,
                'c_zhizhao2' => $c_zhizhao,
                'c_content' => $c_content,
                'c_verify' => 1,
                'c_updatetime' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_company')->where('c_id', $c_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功，请耐心等待审核']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败，请刷新重试']);
            }
        }
        $c_id = input('c_id');
        $info = Db::table('up_company')
            ->where('c_id',$c_id)
            ->find();
        //
        // 省
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        // 市
        $city = Db::table('up_area')
            ->where('level', 2)
            ->where('pid', $info['c_sheng'])
            ->field('district_id, district')
            ->select();
        // 区
        $district = Db::table('up_area')
            ->where('level', 3)
            ->where('pid', $info['c_shi'])
            ->field('district_id, district')
            ->select();
        $this->assign([
            'info' => $info,
            'province' => $province,
            'city' => $city,
            'district' => $district
        ]);
        return $this->fetch('/update');
    }
    /**
     * place 三级联动
     * @return \think\response\Json
     */
    public function place()
    {
        $area = new \app\common\place\Area;
        $data = $area->area();
        return json($data);
    }
    /**
     * upload 上传图片到七牛云
     *
     */
    public function upload(){
        $configconfig = [
            'region' => config('tengx')['region'],
            'schema' => config('tengx')['schema'], //协议头部，默认为http
            'credentials'=> array(
                'secretId'  => config('tengx')['secretId'] ,
                'secretKey' => config('tengx')['secretKey']
            )
        ];
        $cosClient = new Client($configconfig);
        $filePath = $_FILES['file']['tmp_name'];
        $type = explode(".",$_FILES['file']['name']);
        $type = end($type);
        //组装图片名
        $key = md5(time().uuid()).'.'.$type;
        try {
            $result = $cosClient->putObject(array(
                'Bucket' => config('tengx')['Bucket'], //格式：BucketName-APPID
                'Key' => $key,
                'Body' => fopen($filePath, 'rb'),
            ));
            // 请求成功
            echo config('tengx')['domain'] . $key;
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }
    /*
        * wangEditor图片上传
        */
    public function wangUpload(){
        set_time_limit (0);
        foreach($_FILES as $key=>$vo){
            $filePath = $vo['tmp_name'];
            //取出图片后缀
            $type = explode(".",$vo['name']);
            $type = end($type);
            //组装图片名
            $key = md5(time().uuid()).'.'.$type;
            $configconfig = [
                'region' => config('tengx')['region'],
                'schema' => config('tengx')['schema'], //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => config('tengx')['secretId'] ,
                    'secretKey' => config('tengx')['secretKey']
                )
            ];
            $cosClient = new Client($configconfig);
            $result = $cosClient->putObject(array(
                'Bucket' => config('tengx')['Bucket'], //格式：BucketName-APPID
                'Key' => $key,
                'Body' => fopen($filePath, 'rb'),
            ));
            $data[] = config('tengx')['domain'] . $key;
        }
        return json(['errno'=>0,'data'=>$data]);
    }
    //---------------------------------------------------------------------------------------------------------------------
    //------------------------------------ 注册 end -----------------------------------------------------------------------------
    //---------------------------------------------------------------------------------------------------------------------

}